import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:beamer/beamer.dart';
import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/values/images.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/common/repository/favorite_repository.dart';
import 'package:awak/common/repository/user_repository.dart';
import 'package:awak/common/models/content.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/page/community/content_data_holder.dart';
import 'package:awak/page/profile/user_data_holder.dart';
import 'package:awak/common/routers/router_names.dart';

class CollectProfilePage extends StatefulWidget {
  const CollectProfilePage({super.key});

  @override
  State<CollectProfilePage> createState() => _CollectProfilePageState();
}

class _CollectProfilePageState extends State<CollectProfilePage> {
  final FavoriteRepository _favoriteRepository = FavoriteRepository();
  final UserRepository _userRepository = UserRepository();

  List<Content> _favoriteContents = [];
  User? _currentUser;
  Map<int, User> _contentUsersCache = {};
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadFavoriteContents();
  }

  Future<void> _loadFavoriteContents() async {
    try {
      _currentUser = _userRepository.currentUser;

      if (_currentUser?.id != null) {
        // 获取用户收藏的内容
        final contents = await _favoriteRepository.getFavoriteContentsByUserId(
          _currentUser!.id!,
        );

        // 获取内容作者信息
        Map<int, User> usersCache = {};
        Set<int> userIds = contents.map((c) => c.userId).toSet();
        for (int userId in userIds) {
          final user = await _userRepository.getUserById(userId);
          if (user != null) {
            usersCache[userId] = user;
          }
        }

        setState(() {
          _favoriteContents = contents;
          _contentUsersCache = usersCache;
          _isLoading = false;
        });
      } else {
        setState(() {
          _favoriteContents = [];
          _isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        _favoriteContents = [];
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFD7F349),
      body: Column(
        children: [
          SizedBox(height: 40.h),
          // 顶部导航栏
          Padding(
            padding: EdgeInsets.all(16.w),
            child: Row(
              children: [
                GestureDetector(
                  onTap: () {
                    Beamer.of(context).beamBack();
                  },
                  child: Icon(AwakSvg.back),
                ),
                Expanded(
                  child: Center(
                    child: Text('COLLECT', style: AwakText.titleStyle),
                  ),
                ),
                SizedBox(width: 20.w),
              ],
            ),
          ),
          SizedBox(height: 10.h),
          // 用户信息区域
          _buildUserInfoSection(),
          SizedBox(height: 20.h),
          // 内容列表
          Expanded(child: _buildContentList()),
        ],
      ),
    );
  }

  // 构建用户信息区域
  Widget _buildUserInfoSection() {
    if (_currentUser == null) {
      return Container();
    }

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          // 用户头像
          Container(
            width: 50.w,
            height: 50.h,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.black, width: 2.w),
              image: DecorationImage(
                image: AssetImage(_currentUser!.avatar ?? AwakImages.avatar),
                fit: BoxFit.cover,
              ),
            ),
          ),
          SizedBox(width: 12.w),
          // 用户信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _currentUser!.nickname ?? _currentUser!.username,
                  style: AwakText.body18Style.copyWith(
                    color: Colors.black,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  _currentUser!.signature ?? 'Bright Enough To Be Seen',
                  style: AwakText.body14Style.copyWith(
                    color: Colors.black.withValues(alpha: 0.7),
                    fontWeight: FontWeight.w500,
                    fontSize: 12.sp,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建内容列表
  Widget _buildContentList() {
    if (_isLoading) {
      return Center(child: CircularProgressIndicator());
    }

    if (_favoriteContents.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.favorite_border,
              size: 64.w,
              color: Colors.black.withValues(alpha: 0.3),
            ),
            SizedBox(height: 16.h),
            Text(
              'No favorite content yet',
              style: AwakText.body16Style.copyWith(
                color: Colors.black.withValues(alpha: 0.5),
              ),
            ),
          ],
        ),
      );
    }

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: ListView.builder(
        padding: EdgeInsets.all(16.w),
        itemCount: _favoriteContents.length,
        itemBuilder: (context, index) {
          return _buildContentCard(_favoriteContents[index]);
        },
      ),
    );
  }

  // 构建内容卡片
  Widget _buildContentCard(Content content) {
    final user = _contentUsersCache[content.userId];
    final userName = user?.nickname ?? user?.username ?? 'Unknown User';
    final userAvatar = user?.avatar ?? AwakImages.avatar;
    final userSignature = user?.signature ?? 'No signature';

    return GestureDetector(
      onTap: () {
        // 设置当前内容并跳转到内容详情页
        ContentDataHolder.setCurrentContent(content);
        Beamer.of(context).beamToNamed(RouterNames.detailContent);
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 16.h),
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(12.r),
          // border: Border.all(color: Colors.black, width: 2.w),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息行
            Row(
              children: [
                GestureDetector(
                  onTap: () {
                    if (user != null) {
                      UserDataHolder.setCurrentUser(user);
                      Beamer.of(context).beamToNamed(RouterNames.otherProfile);
                    }
                  },
                  child: Container(
                    width: 40.w,
                    height: 40.h,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.black, width: 2.w),
                      image: DecorationImage(
                        image: AssetImage(userAvatar),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        userName,
                        style: AwakText.body16Style.copyWith(
                          color: Colors.black,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      Text(
                        userSignature,
                        style: AwakText.body14Style.copyWith(
                          color: Colors.black.withValues(alpha: 0.6),
                          fontSize: 12.sp,
                        ),
                      ),
                    ],
                  ),
                ),
                // Issue标签
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(100.r),
                    border: Border.all(color: Colors.black, width: 1.w),
                  ),
                  child: Row(
                    children: [
                      Icon(AwakSvg.report, size: 14.sp),
                      SizedBox(width: 4.w),
                      Text(
                        'Issue',
                        style: AwakText.body14Style.copyWith(
                          color: Colors.black,
                          fontWeight: FontWeight.w500,
                          fontSize: 12.sp,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 12.h),
            // 内容图片
            Container(
              width: double.infinity,
              height: 223.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12.r),
                // border: Border.all(color: Colors.black, width: 2.w),
                image: DecorationImage(
                  image: AssetImage(content.picture),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SizedBox(height: 12.h),
            // 内容描述
            Text(
              content.description,
              style: AwakText.body16Style.copyWith(
                color: Colors.black,
                fontWeight: FontWeight.w500,
                height: 1.4,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    );
  }
}
